<?php

namespace App\Master\POST;

class Login extends \App\Master\Common {

    public function __init() {
        parent::__init();
        if ($this->login === true && ACTION !== 'logout') {
            $this->jump('/');
        }
        if (ACTION != 'logout') {
            $this->checkVerify();
        }
    }

    /**
     * 注册帐号
     */
    public function signup() {
        $data['user_name'] = $this->isP('name', '请填写名字');
        $data['user_mail'] = $this->isP('mail', '请填写邮箱地址');
        foreach ($data as $key => $value) {
            $check = \Model\Content::findContent('user', $value, $key);
            if (!empty($check)) {
                switch ($key) {
                    case 'user_mail':
                        $msg = "{$value}邮箱以存在";
                        break;
                    case 'user_name':
                        $msg = "{$value}名字以存在";
                        break;
                }
                $this->error($msg);
            }
        }
        $data['user_passwd'] = \Core\Func\CoreFunc::generatePwd($data['user_mail'] . $this->isP('passwd', '请提交密码'), 'PRIVATE_KEY');

        if ($_POST['passwd'] !== $_POST['repasswd']) {
            $this->error('两次密码不一致.');
        }

        $data['user_signup_time'] = time();

        \Core\Func\CoreFunc::$defaultPath = false;
        require PES_PATH . '/Expand/Identicon/autoload.php';
        $identicon = new \Identicon\Identicon();
        $data['user_head'] = $identicon->getImageDataUri($data['user_mail']);

        $signupResult = $this->db('user')->insert($data);

        if ($signupResult === false) {
            $this->error('创建帐号失败');
        }
        $data['user_id'] = $signupResult;

        $this->setLogin($data);

        $this->success('注册帐号成功!', '/');
    }

    /**
     * 登录帐号
     */
    public function login() {
        $data['user_mail'] = $this->isP('mail', '请填写邮箱地址');
        $data['user_passwd'] = \Core\Func\CoreFunc::generatePwd($data['user_mail'] . $this->isP('passwd', '请提交密码'), 'PRIVATE_KEY');
        $check = $this->db('user')->where('user_mail = :user_mail AND user_passwd = :user_passwd ')->find($data);
        if (empty($check)) {
            $this->error('帐号不存在或者密码错误');
        }
        $this->setLogin($check);

        if (!empty($_GET['back_url'])) {
            $url = base64_decode($this->g('back_url'));
        } else {
            $url = '/';
        }

        $this->success('登录成功', $url);
    }

    /**
     * 安全退出
     */
    public function logout() {
        $this->db('login_user')->where('login_cookie = :login_cookie AND user_id = :user_id')->delete([
            'login_cookie' => $_COOKIE['tm'],
            'user_id' => $_SESSION['user']['user_id']
        ]);
        setcookie('tm', NULL, time() - 10, '/');
        session_destroy();
        $this->success('您已安全退出', '/');
    }

    /**
     * 查找密码
     */
    public function findPassword() {
        $mail = $this->isP('mail', '请提交邮箱地址');
        $checkUser = \Model\Content::findContent('user', $mail, 'user_mail');
        if (empty($checkUser)) {
            $this->error('邮箱地址不存在');
        }

        $mark = \Model\Extra::getOnlyNumber();

        $this->db('findpassword')->where('findpassword_createtime < :time')->delete([
            'time' => time() - 86400
        ]);

        //创建标记
        $this->db('findpassword')->insert([
            'user_id' => $checkUser['user_id'],
            'findpassword_mark' => $mark,
            'findpassword_createtime' => time()
        ]);

        //创建邮件
        $mailContent = "<p>尊敬的用户：您已提交找回密码的请求，请点击此链接完成操作：http://www.timelog.xyz" . $this->url('Master-Login-setPassword', ['mark' => $mark]) . "</p>
                        <p>友情提醒：本链接1天内有效。</p>
                        <p>请勿回复本邮箱，即使你回复，我也不会回应你的！</p>";
        $this->db('send')->insert([
            'send_account' => $checkUser['user_mail'],
            'sned_title' => 'Timelog登录账号密码找回',
            'send_content' => $mailContent,
            'send_time' => time(),
            'send_type' => '1',
        ]);

        $this->success('系统已将找回密码的信息发至您的邮箱，请注意查收。');

    }

    /**
     * 重置密码
     */
    public function setPassword() {
        $mark = $this->isG('mark', '请提交正确的MARK');
        $checkMark = $this->db('findpassword')->where('findpassword_createtime >= :time AND findpassword_mark = :findpassword_mark ')->find([
            'time' => time() - 86400,
            'findpassword_mark' => $mark
        ]);
        if (empty($checkMark)) {
            $this->error('MARK不存在', '/');
        }

        $password = $this->isP('passwd', '请输入新密码');
        $repasswd = $this->isP('repasswd', '请输入确认新密码');

        if ($password !== $repasswd) {
            $this->error('两次密码不正确');
        }

        $user = \Model\Content::findContent('user', $checkMark['user_id'], 'user_id');

        $data['noset']['user_id'] = $checkMark['user_id'];
        $data['user_passwd'] = \Core\Func\CoreFunc::generatePwd($user['user_mail'] . $password, 'PRIVATE_KEY');

        $this->db('user')->where('user_id = :user_id')->update($data);

        $this->db('findpassword')->where('findpassword_id = :id')->delete([
            'id' => $checkMark['findpassword_id']
        ]);

        $this->success('密码修改成功!', $this->url('Master-Login-login'));
    }

}
